import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:龙宝
 * Date:2022-12-17
 * Time:13:09
 */
@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //按照约定接口格式返回数据

        //在博客列表页中，已经使用了BlogServlet。doget
        //使用queryString区分
        resp.setContentType("application/json; charset=utf8");
        String blogId = req.getParameter("blogId");

        BlogDao blogDao = new BlogDao();
        if(blogId == null) {
            //博客列表页
            List<Blog> blogs = blogDao.selectAll();
            resp.getWriter().write(objectMapper.writeValueAsString(blogs));
        } else {
            //博客详情页
            Blog blog = blogDao.selectOne(Integer.parseInt(blogId));
            resp.getWriter().write(objectMapper.writeValueAsString(blog));
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //使用这个方法，来实现提交新博客
        //1、先检查一下用户的登录状态，获取到回话和用户信息
        //如果未登录，不能提交博客
        HttpSession session = req.getSession(false);
        if(session == null) {
            resp.setStatus(403);
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("当前未登录，不能发布博客");
            return;
        }
        User user = (User) session.getAttribute("user");
        if(user == null) {
            resp.setStatus(403);
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("当前未登录，不能发布博客");
            return;
        }
        //2、获取请求中的参数，（博客的标题和正文）
        req.setCharacterEncoding("utf8");
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        //3、构造Blog对象，并且插入到数据库中
        Blog blog = new Blog();
        blog.setTitle(title);
        blog.setContent(content);
        blog.setUserId(user.getUserId());
        //blogId是自增主键，不需要设置   postTime直接在数据库中操作Now操作了
        BlogDao blogDao = new BlogDao();
        blogDao.insert(blog);
        //4、构造重定向报文，回到博客列表页
        resp.sendRedirect("blog_list.html");
    }
}
